package com.cn.onetrip.activity;

import java.text.BreakIterator;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cn.onetrip.objects.AdvertsObj;
import com.cn.onetrip.activity.R;
import com.cn.onetrip.untility.ActivityTag;
import com.cn.onetrip.untility.HTTPUrl;
import com.cn.onetrip.untility.ImageUtils;
import com.cn.onetrip.untility.NetworkManager;
import com.cn.onetrip.untility.ParsonJsonUtility;
import com.cn.onetrip.untility.SyncImageLoader;
import com.cn.onetrip.untility.SysApplication;
import com.cn.onetrip.untility.Untility;
import com.cn.onetrip.untility.SyncImageLoader.OnImageLoadListener;
import com.cn.onetrip.untility.upload;

import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class GroupActivity extends ActivityGroup {

	public ActivityGroup group;
	private SyncImageLoader syncImageLoader;
	public static HashMap<String, Drawable> drawablesCache = new HashMap<String, Drawable>();
	public static boolean one_trip = false;
	// private RelativeLayout layoutProgress;

	private int connectCount = 0;
	private boolean isOfflineData = false;
	private int mCenterX, mCenterY;
	ProgressBar pb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getApplicationContext().getExternalFilesDir("ScenicGuideApp");
		try {
			HTTPUrl.JsonTextFloder = getApplicationContext()
					.getExternalFilesDir("/ScenicGuideApp/JsonText/")
					.getAbsolutePath();
			HTTPUrl.ImageCacheFloder = getApplicationContext()
					.getExternalFilesDir("ScenicGuideApp/ImageCache/")
					.getAbsolutePath();
		} catch (NullPointerException e) {
			HTTPUrl.JsonTextFloder = Environment.getExternalStorageDirectory()
					.getAbsolutePath();
			HTTPUrl.ImageCacheFloder = Environment
					.getExternalStorageDirectory().getAbsolutePath();
		}

		setContentView(R.layout.activity_group);
		group = this;

		Toast.makeText(group, "" + one_trip, Toast.LENGTH_SHORT).show();

		pb = (ProgressBar) findViewById(R.id.group_pb);

		DisplayMetrics dm = new DisplayMetrics();
		dm = getResources().getDisplayMetrics();
		mCenterX = dm.widthPixels / 2;
		mCenterY = dm.heightPixels / 2;

		if (!NetworkManager.CheckWifiState(getApplicationContext())) {
			String json1 = SysApplication.Json1Path;
			String json2 = SysApplication.Json2Path;
			ParsonJsonUtility parsonUtility = new ParsonJsonUtility(group);
			parsonUtility.parsonJsonAll(ImageUtils.readFile(json1));
			parsonUtility.parsonJsonInfo(ImageUtils.readFile(json2), false);
			intentToActivity();
			return;
		}

		if (checkPixel()) {
			startLoadingData();
		} else {
			widthPixelsTips();
		}
	}

	private boolean checkPixel() {
		DisplayMetrics displayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

		if (displayMetrics.widthPixels < getResources().getInteger(
				R.integer.min_displayMetrics_widthpixel)) {
			return false;
		} else {
			return true;
		}
	}

	public void widthPixelsTips() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle(R.string.width_pixel_warring);
		builder.setMessage(R.string.width_pixel_warring_info);
		builder.setNegativeButton(R.string.width_pixel_configm,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						startLoadingData();
					}
				});
		builder.setPositiveButton(R.string.quit, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				android.os.Process.killProcess(android.os.Process.myPid());
				finish();
			}
		});
		builder.create();
		builder.show();
	}

	private void startLoadingData() {
		if (!HTTPUrl.CheckNetworkState(getApplicationContext())
				&& !isOfflineData) {
			NetworkManager.NetworkTips(this);
		} else if (!HTTPUrl.CheckNetworkState(getApplicationContext())
				&& isOfflineData) {

		} else if (HTTPUrl.CheckNetworkState(getApplicationContext())
				&& isOfflineData) {
			// layoutProgress.setVisibility(View.VISIBLE);
			startInfoLoadThread();
		} else {
			// layoutProgress.setVisibility(View.VISIBLE);
			startContentLoadThread();
		}
	}

	private void startContentLoadThread() {
		ContentDataThread slugDatathread = new ContentDataThread(
				HTTPUrl.HTTP_CONTENT_URL);
		Thread thread = new Thread(slugDatathread);
		thread.start();
	}

	public class ContentDataThread implements Runnable {
		String url;

		public ContentDataThread(String url) {
			this.url = url;
		}

		@Override
		public void run() {
			try {
				new Thread().sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (connectCount == 3) {
				Message msg = new Message();
				msg.what = 3;
				msg.obj = "exit";
				contentDatahandler.sendMessage(msg);
			} else {
				new upload(contentDatahandler).Http_Get_Content(url);
			}
			connectCount++;
		}
	}

	public Handler contentDatahandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {

			if (msg.what == 0) {
				String responseJson = (String) msg.obj;
				if (responseJson != null && responseJson.length() != 0) {
					ParsonJsonUtility parsonUtility = new ParsonJsonUtility(
							group);
					parsonUtility.parsonJsonAll(responseJson);

					startInfoLoadThread();
				}
			} else if (msg.what == 1) {
				startContentLoadThread();
			} else if (msg.what == 3) {
				NetworkManager.NetworkTips(GroupActivity.this);
			}
		};
	};

	private void startInfoLoadThread() {
		InfoDataThread slugDatathread = new InfoDataThread(
				HTTPUrl.HTTP_INFO_URL);
		Thread thread = new Thread(slugDatathread);
		thread.start();
	}

	public class InfoDataThread implements Runnable {
		String url;

		public InfoDataThread(String url) {
			this.url = url;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				new Thread().sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (connectCount == 3) {
				Message msg = new Message();
				msg.what = 3;
				msg.obj = "exit";
				infoDatahandler.sendMessage(msg);
			} else {
				new upload(infoDatahandler).Http_Get_Content(url);
			}
			connectCount++;
		}
	}

	public Handler infoDatahandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {

			if (msg.what == 0) {
				String responseJson = (String) msg.obj;
				if (responseJson != null && responseJson.length() != 0) {
					ParsonJsonUtility parsonUtility = new ParsonJsonUtility(
							group);
					parsonUtility.parsonJsonInfo(responseJson, false);

					getAdsImageCache();

					startWeatherLoadThread();

					// Untility.initAnimation(mCenterX, mCenterY);
					// changeFirstView();
				}
			} else if (msg.what == 1) {
				startInfoLoadThread();
			} else if (msg.what == 3) {
			}
		};
	};

	private void startWeatherLoadThread() {
		WeatherDataThread weatherDatathread = new WeatherDataThread(
				HTTPUrl.HTTP_WEATHER_URL);
		Thread thread = new Thread(weatherDatathread);
		thread.start();
	}

	public class WeatherDataThread implements Runnable {
		String url;

		public WeatherDataThread(String url) {
			this.url = url;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				new Thread().sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (connectCount == 3) {
				Message msg = new Message();
				msg.what = 3;
				msg.obj = "exit";
				weatherDatahandler.sendMessage(msg);
			} else {
				new upload(weatherDatahandler).Http_Get_Content(url);
			}
			connectCount++;
		}
	}

	public Handler weatherDatahandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {

			if (msg.what == 0) {
				String responseJson = (String) msg.obj;
				if (responseJson != null && responseJson.length() != 0) {
					ParsonJsonUtility parsonUtility = new ParsonJsonUtility(
							group);
					parsonUtility.parsonJsonWeather(responseJson);

					intentToActivity();
				}
			} else if (msg.what == 1) {
				startWeatherLoadThread();
			} else if (msg.what == 3) {
				intentToActivity();
			}
		};
	};

	private void intentToActivity() {
		pb.setVisibility(View.GONE);

		Intent intent = new Intent(getApplicationContext(), TripActivity.class);
		startActivity(intent);

		finish();
		overridePendingTransition(R.anim.push_right_translate,
				R.anim.pull_left_translate);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	private void getAdsImageCache() {
		syncImageLoader = new SyncImageLoader(GroupActivity.this);
		List<AdvertsObj> advertsList = SysApplication.advertsList;
		for (int i = 0; i < advertsList.size(); i++) {
			final AdvertsObj advertsObj = advertsList.get(i);
			syncImageLoader.loadImage(advertsObj.advert_icon,
					new OnImageLoadListener() {

						@Override
						public void onImageLoad(Drawable drawable) {
							if (drawable != null) {
								drawablesCache.put(advertsObj.advert_icon,
										drawable);
							}
						}

						@Override
						public void onImageLoad(Integer t, Drawable drawable) {
						}

						@Override
						public void onError() {
						}

						@Override
						public void onError(Integer t) {
						}
					});
		}
	}

	// static public void changeFirstView() {
	// Intent intent = new Intent(group, TripActivity.class)
	// .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	// if (intent == null) {
	// return;
	// }
	// Window w = group.getLocalActivityManager().startActivity(
	// ActivityTag.Trip, intent);
	// View view = w.getDecorView();
	// view.startAnimation(Untility.rQuest2Animation);
	// group.setContentView(view);
	// ActivityTag.tag = ActivityTag.Trip;
	// }
	//
	// static public void changeInfoView() {
	// Intent intent = new Intent(group, InfomationActivity.class)
	// .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	// if (intent == null) {
	// return;
	// }
	// Window w = group.getLocalActivityManager().startActivity(
	// ActivityTag.Info, intent);
	// View view = w.getDecorView();
	// view.startAnimation(Untility.lQuest2Animation);
	// group.setContentView(view);
	// ActivityTag.tag = ActivityTag.Info;
	// }
	//
	// static public void changeGalleryView() {
	// Intent intent = new Intent(group, GalleryFlowActivity.class)
	// .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	// if (intent == null) {
	// return;
	// }
	// Window w = group.getLocalActivityManager().startActivity(
	// ActivityTag.Gallery, intent);
	// View view = w.getDecorView();
	// view.startAnimation(Untility.lQuest2Animation);
	// group.setContentView(view);
	// ActivityTag.tag = ActivityTag.Gallery;
	// }
	//
	// static public void changeRouteView() {
	// Intent intent = new Intent(group, RouteActivity.class)
	// .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	// if (intent == null) {
	// return;
	// }
	// Window w = group.getLocalActivityManager().startActivity(
	// ActivityTag.Route, intent);
	// View view = w.getDecorView();
	// view.startAnimation(Untility.lQuest2Animation);
	// group.setContentView(view);
	// ActivityTag.tag = ActivityTag.Route;
	// }
	//
	// static public void changeExpenseView() {
	// Intent intent = new Intent(group, PlayViewPagerActivity.class)
	// .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	// if (intent == null) {
	// return;
	// }
	// Window w = group.getLocalActivityManager().startActivity(
	// ActivityTag.Expense, intent);
	// View view = w.getDecorView();
	// view.startAnimation(Untility.lQuest2Animation);
	// group.setContentView(view);
	// ActivityTag.tag = ActivityTag.Expense;
	// }
	//
	// static public void changeMoreView() {
	// Intent intent = new Intent(group, MoreActivity.class)
	// .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	// if (intent == null) {
	// return;
	// }
	// Window w = group.getLocalActivityManager().startActivity(
	// ActivityTag.More, intent);
	// View view = w.getDecorView();
	// view.startAnimation(Untility.lQuest2Animation);
	// group.setContentView(view);
	// ActivityTag.tag = ActivityTag.More;
	// }
	//
	// static public void changeVideoView() {
	// Intent intent = new Intent(group, VideosActivity.class)
	// .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	// if (intent == null) {
	// return;
	// }
	// Window w = group.getLocalActivityManager().startActivity(
	// ActivityTag.Videos, intent);
	// View view = w.getDecorView();
	// view.startAnimation(Untility.lQuest2Animation);
	// group.setContentView(view);
	// ActivityTag.tag = ActivityTag.Videos;
	// }
	//
	// static public void changeTravelView() {
	// Intent intent = new Intent(group, TravelActivity.class)
	// .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	// if (intent == null) {
	// return;
	// }
	// Window w = group.getLocalActivityManager().startActivity(
	// ActivityTag.Travel, intent);
	// View view = w.getDecorView();
	// view.startAnimation(Untility.lQuest2Animation);
	// group.setContentView(view);
	// ActivityTag.tag = ActivityTag.Travel;
	// }

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// if (ActivityTag.tag.equals(ActivityTag.Trip)) {
			System.gc();
			finish();
			// android.os.Process.killProcess(android.os.Process.myPid());
			// java.lang.System.exit(0);
			// } else if (ActivityTag.tag.equals(ActivityTag.Info)) {
			// InfomationActivity.view
			// .startAnimation(Untility.rQuest1Animation);
			// GroupActivity.changeFirstView();
			// return true;
			// } else if (ActivityTag.tag.equals(ActivityTag.Gallery)) {
			// GalleryFlowActivity.view
			// .startAnimation(Untility.rQuest1Animation);
			// GroupActivity.changeFirstView();
			// return true;
			// } else if (ActivityTag.tag.equals(ActivityTag.Route)) {
			// RouteActivity.view.startAnimation(Untility.rQuest1Animation);
			// GroupActivity.changeFirstView();
			// return true;
			// } else if (ActivityTag.tag.equals(ActivityTag.Expense)) {
			// PlayViewPagerActivity.view
			// .startAnimation(Untility.rQuest1Animation);
			// GroupActivity.changeFirstView();
			// return true;
			// } else if (ActivityTag.tag.equals(ActivityTag.More)) {
			// MoreActivity.view.startAnimation(Untility.rQuest1Animation);
			// GroupActivity.changeFirstView();
			// return true;
			// } else if (ActivityTag.tag.equals(ActivityTag.Travel)) {
			// TravelActivity.view.startAnimation(Untility.rQuest1Animation);
			// GroupActivity.changeFirstView();
			// return true;
			// } else if (ActivityTag.tag.equals(ActivityTag.Videos)) {
			// VideosActivity.view.startAnimation(Untility.rQuest1Animation);
			// GroupActivity.changeFirstView();
			// return true;
			// }
		}
		return super.onKeyDown(keyCode, event);
	}
}
